package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/serializer"
	"shop-common/library/variables"
	"shop-common/utils/contextArgs"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
)

type StoreProductRuleController struct {
}

// @Tags 规格管理
// @description: 分页
// @Summary 分页
// @Security ApiKeyAuth
// @function: Page
// @Accept  json
// @Produce  json
// @Param current query string false "当前页，默认1"
// @Param size query string false "每页大小，默认10"
// @Param keyword query string false "keyword"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/rule/page [get]
func (s *StoreProductRuleController) Page(ctx *gin.Context) {
	form := pagehelper.SearchPageRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	var rows []*model.StoreProductRule
	var count int64
	paginator := pagehelper.New().SetOffset(form).SetFilter([]string{"id"}).
		IsPush(form.Keyword != "", queryWrapper.Like("rule_name", form.Keyword)).Paginator()

	tx := queryWrapper.ReuseWherePair(variables.GormDB().Model(&model.StoreProductRule{}), paginator.Params.WherePair)
	tx = tx.Scopes(pagehelper.Paginate(paginator.Params.Current, paginator.Params.Size))
	err := tx.Find(&rows).Error
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	pageDB := queryWrapper.ReuseWherePair(variables.GormDB().Model(&model.StoreProductRule{}), paginator.Params.WherePair)
	err = queryWrapper.ReuseWherePair(pageDB, paginator.Params.WherePair).Count(&count).Error

	if count == 0 {
		serializer.SuccessData(ctx, "", paginator.Record)
		return
	}

	result, err := paginator.Result(rows, count)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}
	serializer.SuccessData(ctx, "", result)
}

// @Tags 规格管理
// @description: 分页
// @Summary 分页
// @Security ApiKeyAuth
// @function: Page
// @Accept  json
// @Produce  json
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/rule/list [get]
func (s *StoreProductRuleController) List(ctx *gin.Context) {
	var rows []*model.StoreProductRule
	if err := variables.GormDB().Model(&model.StoreProductRule{}).Find(&rows).Error; err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	serializer.SuccessData(ctx, "", rows)
}

// @Tags 规格管理
// @Summary 获取规格信息
// @Security ApiKeyAuth
// @function: Info
// @Param ruleId path string true "规格ID"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/rule/info/{id} [get]
func (s *StoreProductRuleController) Info(ctx *gin.Context) {
	ruleId, err := contextArgs.GetUriIntPath(ctx, "ruleId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	var ruleInfo *model.StoreProductRule
	err = variables.GormDB().First(&ruleInfo, uint(ruleId)).Error
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	serializer.SuccessData(ctx, "", ruleInfo)
}

// @Tags 规格管理
// @description: 保存
// @Summary 保存
// @Security ApiKeyAuth
// @function: Save
// @Accept  json
// @Produce  json
// @Param data body request.StoreProductRuleRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/rule [post]
func (s *StoreProductRuleController) Save(ctx *gin.Context) {
	form := request.StoreProductRuleRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	marshal, err := json.Marshal(&form.Spec)
	if err != nil {
		serializer.Fail(ctx, "商品规格不合法")
		return
	}

	var count int64
	err = variables.GormDB().Model(&model.StoreProductRule{}).Where("rule_name = ?", form.RuleName).Count(&count).Error
	if err != nil {
		serializer.Fail(ctx, "数据已存在")
		return
	}

	err = variables.GormDB().Create(&model.StoreProductRule{
		RuleName:  form.RuleName,
		RuleValue: string(marshal),
	}).Error

	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	serializer.Success(ctx, "")
}

// @Tags 规格管理
// @description: 修改
// @Summary 修改
// @Security ApiKeyAuth
// @function: Update
// @Accept  json
// @Produce  json
// @Param data body request.StoreProductRuleRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/rule [put]
func (s *StoreProductRuleController) Update(ctx *gin.Context) {
	form := request.StoreProductRuleRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if form.Id < 1 {
		serializer.Fail(ctx, "id不合法")
		return
	}

	marshal, err := json.Marshal(&form.Spec)
	if err != nil {
		serializer.Fail(ctx, "商品规格不合法")
		return
	}

	var ruleInfo *model.StoreProductRule
	err = variables.GormDB().First(&ruleInfo, form.Id).Error
	if err != nil || ruleInfo == nil {
		serializer.Fail(ctx, "数据不存在")
		return
	}

	err = variables.GormDB().Updates(&model.StoreProductRule{
		Id:        form.Id,
		RuleName:  form.RuleName,
		RuleValue: string(marshal),
	}).Error

	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	serializer.Success(ctx, "")
}

// @Tags 规格管理
// @description: 删除
// @Summary 删除
// @Security ApiKeyAuth
// @function: Delete
// @Accept  json
// @Produce  json
// @Param data body request.CommonBatchRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/rule [delete]
func (s *StoreProductRuleController) Delete(ctx *gin.Context) {
	form := request.CommonBatchRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	err := variables.GormDB().Delete(&model.StoreProductRule{}, form.Ids).Error
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	serializer.Success(ctx, "")
}
